package com.example.administrator.hqq.activity.dating;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.example.administrator.hqq.R;
import com.example.administrator.hqq.View.alertview.AlertView;
import com.example.administrator.hqq.View.alertview.AlertViewFactory;
import com.example.administrator.hqq.View.alertview.OnItemClickListener;
import com.example.administrator.hqq.base.MyActivity;
import com.example.administrator.hqq.bean.QNTokenBean;
import com.example.administrator.hqq.bean.dating.CreatDatingBean;
import com.example.administrator.hqq.bean.event.DatingEvent;
import com.example.administrator.hqq.config.LoongsConfig;
import com.example.administrator.hqq.config.UrlFactory;
import com.example.administrator.hqq.utils.CameraUtils;
import com.example.administrator.hqq.utils.GetLocationUtils;
import com.example.administrator.hqq.utils.HintWordsUtils;
import com.example.administrator.hqq.utils.MyTextUtils;
import com.example.administrator.hqq.utils.SketchTextWatcher;
import com.example.administrator.hqq.utils.UploadManagerUtils;
import com.google.gson.Gson;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class CreatDatingActivity extends MyActivity {

    @BindView(R.id.return_auto)
    AutoRelativeLayout returnAuto;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.report_auto)
    AutoRelativeLayout reportAuto;
    @BindView(R.id.search)
    TextView search;
    @BindView(R.id.issue)
    TextView issue;
    @BindView(R.id.add)
    ImageView add;
    @BindView(R.id.locality)
    RadioButton locality;
    @BindView(R.id.locality_unlimited)
    RadioButton localityUnlimited;
    @BindView(R.id.location_prefer)
    AutoLinearLayout locationPrefer;
    @BindView(R.id.man)
    RadioButton man;
    @BindView(R.id.woman)
    RadioButton woman;
    @BindView(R.id.man_unlimited)
    RadioButton manUnlimited;
    @BindView(R.id.gender_prefer)
    AutoLinearLayout genderPrefer;
    @BindView(R.id.age_young)
    RadioButton ageYoung;
    @BindView(R.id.age_same)
    RadioButton ageSame;
    @BindView(R.id.age_old)
    RadioButton ageOld;
    @BindView(R.id.age_prefer)
    AutoLinearLayout agePrefer;
    @BindView(R.id.introduce)
    EditText introduce;
    @BindView(R.id.scrollView)
    ScrollView scrollView;
    @BindView(R.id.forum_guide)
    ImageView forumGuide;
    private String location_prefer = null;
    private String gender_prefer = null;
    private QNTokenBean qnTokenBean;
    private String TAG = this.getClass().getSimpleName();
    private AlertView photoTypeAlertView;
    private String url = null;
    private Type type;
    private String age_prefer;

    public enum Type {
        CREAT, COMPILE
    }

    public static void start(Context context, String dating_id, Type type) {
        Intent intent = new Intent(context, CreatDatingActivity.class);
        intent.putExtra(LoongsConfig.dating_id, dating_id);
        intent.putExtra(LoongsConfig.type, type);
        context.startActivity(intent);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_creat_dating);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        type = (Type) getIntent().getSerializableExtra(LoongsConfig.type);
        switch (type) {
            case CREAT:
                issue.setText("发布");
                break;
            case COMPILE:
                issue.setText("完成");
                initdata();
                break;
        }
        boolean aBoolean = SPUtils.getInstance().getBoolean(LoongsConfig.first_forum_create, true);
        if (aBoolean) {
            forumGuide.setVisibility(View.VISIBLE);
            SPUtils.getInstance().put(LoongsConfig.first_forum_create, false);
            Handler handler = new Handler();
            handler.post(new Runnable() {
                @Override
                public void run() {
                    scrollView.fullScroll(ScrollView.FOCUS_DOWN);
                }
            });
        }
        initview();
    }

    private void initdata() {
        OkHttpUtils.get().url(UrlFactory.prepareSetDatingInfo())
                .addParams(LoongsConfig.user_id, LoongsConfig.getUser_id())
                .addParams(LoongsConfig.dating_id, getIntent().getStringExtra(LoongsConfig.dating_id))
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "相亲贴子的全部详情onError: " + e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "相亲贴子的全部详情onResponse: " + response);
                Gson gson = new Gson();
                CreatDatingBean creatDatingBean = gson.fromJson(response, CreatDatingBean.class);
                if (creatDatingBean.getCode() == 200) {
                    setScreenContent(creatDatingBean);
                }
            }
        });
    }

    /**
     * 设置筛选项
     *
     * @param creatDatingBean
     */
    private void setScreenContent(CreatDatingBean creatDatingBean) {
        age_prefer = creatDatingBean.getData().getAge_type();
        gender_prefer = creatDatingBean.getData().getGender_prefer() + "";
        location_prefer = creatDatingBean.getData().getLocation_prefer() + "";
        introduce.setText(creatDatingBean.getData().getText());
        url = "";
        Glide.with(this).load(creatDatingBean.getData().getUrl()).into(add);
        String[] split = age_prefer.split(",");
        for (String s : split) {
            if (s.equals("YOUNGER")) {
                ageYoung.setSelected(false);
                setSelectedAge(ageYoung);
            } else if (s.equals("SAME")) {
                ageSame.setSelected(false);
                setSelectedAge(ageSame);
            } else {
                ageOld.setSelected(false);
                setSelectedAge(ageOld);
            }
        }
        switch (gender_prefer) {
            case "0":
                setGreenTextColor(manUnlimited);
                setBlackTextColor(man);
                setBlackTextColor(woman);
                break;
            case "1":
                setGreenTextColor(man);
                setBlackTextColor(woman);
                setBlackTextColor(manUnlimited);
                break;
            case "2":
                setGreenTextColor(woman);
                setBlackTextColor(man);
                setBlackTextColor(manUnlimited);
                break;
        }
        if (location_prefer.equals("1")) {
            setBlackTextColor(localityUnlimited);
            setGreenTextColor(locality);
        } else {
            setBlackTextColor(locality);
            setGreenTextColor(localityUnlimited);
        }
    }

    @Override
    protected String getActivityName() {
        return this.getClass().getSimpleName();
    }

    private void initview() {
        issue.setVisibility(View.VISIBLE);
        introduce.addTextChangedListener(new SketchTextWatcher(introduce, 150 * 3));
    }

    @OnClick({R.id.forum_guide,R.id.return_auto, R.id.issue, R.id.add, R.id.locality, R.id.locality_unlimited, R.id.man, R.id.woman, R.id.man_unlimited, R.id.age_young, R.id.age_same, R.id.age_old})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.forum_guide:
                forumGuide.setVisibility(View.GONE);
                break;
            case R.id.return_auto:
                finish();
                break;
            case R.id.issue:
                switch (type) {
                    case CREAT:
                        CreatDating();
                        break;
                    case COMPILE:
                        compileDating();
                        break;
                }
                break;
            case R.id.add:
                //选择拍摄或者相册
                photoTypeAlertView = AlertViewFactory.getInstance().getPhotoTypeAlertView(CreatDatingActivity.this, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        if (position == -1) {
                            photoTypeAlertView.dismiss();
                        } else if (position == 0) {
                            CreatDatingActivityPermissionsDispatcher.startLocationWithCheck(CreatDatingActivity.this);
                        } else if (position == 1) {
                            CreatDatingActivityPermissionsDispatcher.startStorageWithCheck(CreatDatingActivity.this);
                        }
                    }
                });
                photoTypeAlertView.show();
                break;
        }
        setDatingScreenClicked(view);
    }

    /**
     * 修改相亲贴子
     */
    private void compileDating() {
        age_prefer = null;
        ArrayList<String> strings = new ArrayList<>();
        if (url == null) {
            ToastUtils.showShort("请上传一张自己的照片");
            return;
        }
        if (TextUtils.isEmpty(introduce.getText())) {
            ToastUtils.showShort("请做简单的自我介绍");
            return;
        }
        if (TextUtils.isEmpty(location_prefer)) {
            ToastUtils.showShort("请选择地区限制");
            return;
        }
        if (TextUtils.isEmpty(gender_prefer)) {
            ToastUtils.showShort("请选择性别限制");
        }
        if (ageYoung.isSelected()) {
            strings.add("YOUNGER");
        }
        if (ageSame.isSelected()) {
            strings.add("SAME");
        }
        if (ageOld.isSelected()) {
            strings.add("OLDER");
        }
        if (strings.size() == 0) {
            ToastUtils.showShort("请选择年龄限制");
            return;
        } else {
            for (int i = 0; i < strings.size(); i++) {
                if (i == 0) {
                    age_prefer = strings.get(i);
                } else {
                    age_prefer += "," + strings.get(i);
                }
            }
        }
        showLoadingDialog();
        OkHttpUtils.get().url(UrlFactory.setDatingInfo())
                .addParams(LoongsConfig.dating_id, getIntent().getStringExtra(LoongsConfig.dating_id))
                .addParams(LoongsConfig.user_id, LoongsConfig.getUser_id())
                .addParams(LoongsConfig.location, GetLocationUtils.getLocation())
                .addParams(LoongsConfig.city_code, GetLocationUtils.getCityCode())
                .addParams(LoongsConfig.location_prefer, location_prefer)
                .addParams(LoongsConfig.gender_prefer, gender_prefer)
                .addParams(LoongsConfig.age_prefer, age_prefer)
                .addParams(LoongsConfig.text, introduce.getText().toString())
                .addParams(LoongsConfig.url, url)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                dismissLoadingDialog();
                Log.e(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                dismissLoadingDialog();
                Log.e(TAG, "onResponse: " + response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int code = jsonObject.getInt(LoongsConfig.code);
                    HintWordsUtils.showMarkeWords(code,jsonObject.getString(LoongsConfig.description));
                    if (code == 200) {
                        DatingEvent datingEvent = new DatingEvent(DatingEvent.DatingType.COMPILE);
                        EventBus.getDefault().post(datingEvent);
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 发布相亲贴子
     */
    private void CreatDating() {
        age_prefer = null;
        ArrayList<String> strings = new ArrayList<>();
        if (TextUtils.isEmpty(url)) {
            ToastUtils.showShort("请上传一张自己的照片");
            return;
        }
        if (TextUtils.isEmpty(introduce.getText())) {
            ToastUtils.showShort("请做简单的自我介绍");
            return;
        }
        if (MyTextUtils.isEmptyString(introduce)){
            ToastUtils.showShort("自我介绍不能全为空格");
            return;
        }
        if (TextUtils.isEmpty(location_prefer)) {
            ToastUtils.showShort("请选择地区限制");
            return;
        }
        if (TextUtils.isEmpty(gender_prefer)) {
            ToastUtils.showShort("请选择性别限制");
        }
        if (ageYoung.isSelected()) {
            strings.add("YOUNGER");
        }
        if (ageSame.isSelected()) {
            strings.add("SAME");
        }
        if (ageOld.isSelected()) {
            strings.add("OLDER");
        }
        if (strings.size() == 0) {
            ToastUtils.showShort("请选择年龄限制");
            return;
        } else {
            for (int i = 0; i < strings.size(); i++) {
                if (i == 0) {
                    age_prefer = strings.get(i);
                } else {
                    age_prefer += "," + strings.get(i);
                }
            }
        }
        OkHttpUtils.get().url(UrlFactory.addDating())
                .addParams(LoongsConfig.dating_id, getIntent().getStringExtra(LoongsConfig.dating_id))
                .addParams(LoongsConfig.user_id, LoongsConfig.getUser_id())
                .addParams(LoongsConfig.location, GetLocationUtils.getLocation())
                .addParams(LoongsConfig.city_code, GetLocationUtils.getCityCode())
                .addParams(LoongsConfig.location_prefer, location_prefer)
                .addParams(LoongsConfig.gender_prefer, gender_prefer)
                .addParams(LoongsConfig.age_prefer, age_prefer)
                .addParams(LoongsConfig.text, introduce.getText().toString())
                .addParams(LoongsConfig.url, url)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "发布相亲角onError: ," + e.getMessage());
                ToastUtils.showShort("发布失败");
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "发布相亲角onResponse: " + response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int code = jsonObject.getInt(LoongsConfig.code);
                    HintWordsUtils.showMarkeWords(code,jsonObject.getString(LoongsConfig.description));
                    if (code == 200) {
                        EventBus.getDefault().post(new DatingEvent(DatingEvent.DatingType.CREAD));
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 设置筛选项的点击事件
     *
     * @param view
     */
    private void setDatingScreenClicked(View view) {
        switch (view.getId()) {
            case R.id.locality:
                location_prefer = "1";
                setBlackTextColor(localityUnlimited);
                setGreenTextColor(locality);
                break;
            case R.id.locality_unlimited:
                location_prefer = "0";
                setBlackTextColor(locality);
                setGreenTextColor(localityUnlimited);
                break;
            case R.id.man:
                gender_prefer = "1";
                setGreenTextColor(man);
                setBlackTextColor(woman);
                setBlackTextColor(manUnlimited);
                break;
            case R.id.woman:
                gender_prefer = "2";
                setGreenTextColor(woman);
                setBlackTextColor(man);
                setBlackTextColor(manUnlimited);
                break;
            case R.id.man_unlimited:
                gender_prefer = "0";
                setGreenTextColor(manUnlimited);
                setBlackTextColor(man);
                setBlackTextColor(woman);
                break;
            case R.id.age_young:
                setSelectedAge(ageYoung);
                break;
            case R.id.age_same:
                setSelectedAge(ageSame);
                break;
            case R.id.age_old:
                setSelectedAge(ageOld);
                break;
            case R.id.confirm:
                break;
        }
    }

    /**
     * 设置年龄限制
     *
     * @param radioButton
     */
    private void setSelectedAge(RadioButton radioButton) {
        radioButton.setSelected(!radioButton.isSelected());
        if (radioButton.isSelected()) {
            setGreenTextColor(radioButton);
        } else {
            setBlackTextColor(radioButton);
        }
    }

    private void setGreenTextColor(RadioButton radioButton) {
        radioButton.setTextColor(Color.parseColor("#00AE9D"));
    }

    private void setBlackTextColor(RadioButton radioButton) {
        radioButton.setTextColor(Color.parseColor("#000000"));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e(TAG, "onActivityResult: " + data);
        CameraUtils.getInstance().onActivityResult(this, requestCode, resultCode, data, new CameraUtils.OnResultListener() {
            @Override
            public void takePhotoFinish(String path) {
                File picFile = new File(path);
                if (picFile.exists()) {
                    getQNToken(path);
                }
            }

            @Override
            public void selectPictureFinish(String path) {
                File picFile = new File(path);
                if (picFile.exists()) {
                    getQNToken(path);
                }
            }

            @Override
            public void cropPictureFinish(String path) {

            }
        });
    }

    public void getQNToken(String path) {
        showLoadingDialog();
        final File picFile = new File(path);
        OkHttpUtils.get().url(UrlFactory.getQNToken())
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.type, LoongsConfig.DATING)
                .addParams(LoongsConfig.id, getIntent().getStringExtra(LoongsConfig.dating_id))
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "onError: " + e.getMessage());
                dismissLoadingDialog();
            }

            @Override
            public void onResponse(String s, int id) {
                Log.e(TAG, "onResponse: " + s);
                final Gson gson = new Gson();
                qnTokenBean = gson.fromJson(s, QNTokenBean.class);
                if (qnTokenBean.getCode() == 200) {
                    UploadManagerUtils.getUploadManager().put(picFile, qnTokenBean.getKey(), qnTokenBean.getToken(), new UpCompletionHandler() {
                        @Override
                        public void complete(String key, ResponseInfo info, JSONObject res) {
                            //res包含hash、key等信息，具体字段取决于上传策略的设置
                            if (info.isOK()) {
                                Log.i("qiniu", "res");
                                url = qnTokenBean.getId();
                                Log.e(TAG, "Url: " + qnTokenBean.getUrl());
                                Glide.with(CreatDatingActivity.this)
                                        .load(qnTokenBean.getUrl())
                                        .fitCenter().into(add);
                            } else {
                            }
                            dismissLoadingDialog();
                            Log.e("qiniu", key + ", " + info + ", " + res);
                        }
                    }, null);
                } else {
                    dismissLoadingDialog();

                }
            }
        });
    }

    /**
     * 申请权限
     */
    @SuppressLint("NoCorrespondingNeedsPermission")
    @OnShowRationale({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showRationaleForLocation(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setMessage("申请相机权限")
                .setPositiveButton("同意", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    @OnPermissionDenied({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showDeniedForLocation() {
        Toast.makeText(this, getString(R.string.permission_denied), Toast.LENGTH_SHORT).show();
    }

    @OnNeverAskAgain({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showNeverAskForLocation() {
        Toast.makeText(this, getString(R.string.permission_never_ask), Toast.LENGTH_SHORT).show();
    }

    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    public void startLocation() {
        CameraUtils.getInstance().takeCamera(this);
    }

    @OnShowRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void showRetionaleForStorage(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setMessage(getString(R.string.storage_permission))
                .setPositiveButton(getString(R.string.agree), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton(getString(R.string.refuse), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    @OnNeverAskAgain(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void showNeverAskForStorage() {
        Toast.makeText(this, getString(R.string.permission_never_ask), Toast.LENGTH_SHORT).show();
    }

    @OnPermissionDenied(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void showDeniedForStorage() {
        Toast.makeText(this, getString(R.string.permission_denied), Toast.LENGTH_SHORT).show();
    }

    @NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    public void startStorage() {
        CameraUtils.getInstance().openAlbum(this);
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        CreatDatingActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(String s) {

    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
